package com.coflxl.web.plugins;

import org.sagacity.sqltoy.model.IgnoreCaseSet;
import org.sagacity.sqltoy.model.MapKit;
import org.sagacity.sqltoy.plugins.IUnifyFieldsHandler;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @description 统一字段赋值范例
 */
public class SqlToyUnifyFieldsHandler implements IUnifyFieldsHandler {
    private String defaultUserName = "system-auto";

    /*
     * (non-Javadoc)
     *
     * @see com.sagframe.sqltoy.plugin.IUnifyFieldsHandler#createUnifyFields()
     */
    @Override
    public Map<String, Object> createUnifyFields() {
        LocalDateTime nowTime = LocalDateTime.now();
        // 获取用户信息
        String userId = getUserId();
        return MapKit.keys("createBy", "createTime", "updateBy", "updateTime", "enabled").values(userId, nowTime,
                userId, nowTime, 1);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.sagframe.sqltoy.plugin.IUnifyFieldsHandler#updateUnifyFields()
     */
    @Override
    public Map<String, Object> updateUnifyFields() {
        // 获取用户信息，不存在的字段名称会自动忽略掉(因此下述属性未必是每个表中必须存在的)
        return MapKit.keys("updateBy", "updateTime").values(getUserId(), LocalDateTime.now());
    }

    /**
     * 强制修改的字段，如果没有强制修改，直接返回null
     */
    @Override
    public IgnoreCaseSet forceUpdateFields() {
        IgnoreCaseSet forceUpdateFields = new IgnoreCaseSet();
        forceUpdateFields.add("updateTime");
        return forceUpdateFields;
    }

    /**
     * @return
     * @todo 获取当前用户Id信息
     */
    private String getUserId() {
        // 实际项目一般通过ThreadLocal+Filter方式存放和获取当前用户信息
        // 比如spring-security
        // return (SpringSecurityUtils.getCurrentUser() != null) ? SpringSecurityUtils.getCurrentUser().getId() : defaultUserName;
        return defaultUserName;
    }
}